<template>
  <div class="playlist-detail-container">
    <!-- 返回按钮 -->
    <el-button
      class="back-button"
      type="default"
      icon="el-icon-arrow-left"
      @click="goBack"
      style="margin-bottom: 20px"
    >
      返回
    </el-button>
    <!-- 歌单头部信息 -->
    <div class="playlist-header">
      <div class="cover-container">
        <el-image :src="playlist.coverUrl" class="playlist-cover" fit="cover">
          <template #error>
            <div class="cover-error">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <div class="play-count">
          <el-icon><Headset /></el-icon>
          <span>{{ formatPlayCount(playlist.playCount) }}</span>
        </div>
      </div>

      <div class="playlist-info">
        <h1 class="playlist-title">{{ playlist.name }}</h1>
        <div class="creator-info">
          <el-avatar
            :src="creator.avatarUrl"
            size="small"
            class="creator-avatar"
          />
          <span class="creator-name">{{ creator.nickname }}</span>
          <span class="create-time"
            >{{ formatDate(playlist.createTime) }} 创建</span
          >
        </div>

        <div class="action-buttons">
          <el-button type="primary" class="play-button" round @click="playAll">
            <el-icon><VideoPlay /></el-icon> 播放全部
          </el-button>
          <el-button class="collect-button" round>
            <el-icon><Star /></el-icon> 收藏 ({{ playlist.collectCount }})
          </el-button>
          <el-button class="share-button" round>
            <el-icon><Share /></el-icon> 分享
          </el-button>
        </div>

        <div class="tags-container">
          <el-tag
            v-for="(tag, index) in playlist.tags"
            :key="index"
            type="info"
            size="small"
          >
            {{ tag }}
          </el-tag>
        </div>

        <div class="description">
          <p>{{ playlist.description }}</p>
        </div>
      </div>
    </div>

    <!-- 歌单歌曲列表 -->
    <div class="songs-section">
      <h2 class="section-title">歌曲列表</h2>
      <el-table :data="songs" style="width: 100%" class="songs-table" stripe>
        <el-table-column type="index" width="50" label="#" />
        <el-table-column label="歌曲标题" min-width="300">
          <template #default="{ row }">
            <!-- 添加点击事件跳转到歌曲详情页 -->
            <div class="song-title" @click="goToSongDetail(row.id)">
              <span class="name">{{ row.songName }}</span>
              <span v-if="row.isVip" class="vip-tag">VIP</span>
              <el-icon class="song-link-icon"><Link /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="artistName" label="歌手" min-width="150" />
        <el-table-column prop="albumName" label="专辑" min-width="200" />
        <el-table-column
          prop="duration"
          label="时长"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <div
              style="
                display: flex;
                gap: 8px;
                justify-content: center;
                align-items: center;
              "
            >
              <el-button
                type="primary"
                size="small"
                icon="VideoPlay"
                circle
                @click="playSong(row)"
              />
              <el-button
                type="success"
                size="small"
                icon="Plus"
                circle
                @click="addToPlaylist(row)"
              />
              <el-button
                type="warning"
                size="small"
                icon="Star"
                circle
                @click="likeSong(row)"
              />
              <el-button
                type="info"
                size="small"
                icon="Share"
                circle
                @click="shareSong(row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
      <h2 class="section-title">
        评论 <span class="comment-count">({{ playlist.commentCount }})</span>
      </h2>

      <div class="comment-input">
        <el-avatar
          :src="currentUser.avatarUrl"
          size="default"
          class="user-avatar"
        />
        <div class="input-container">
          <el-input
            v-model="newComment"
            placeholder="分享你的听歌感受..."
            :rows="3"
            type="textarea"
            resize="none"
          />
          <div class="comment-actions">
            <div class="expression-icons">
              <el-icon><Smile /></el-icon>
              <el-icon><MuteNotification /></el-icon>
            </div>
            <el-button type="primary" size="small" class="submit-button"
              >评论</el-button
            >
          </div>
        </div>
      </div>

      <div class="hot-comments">
        <div class="comment-item" v-for="comment in comments" :key="comment.id">
          <el-avatar
            :src="comment.user.avatarUrl"
            size="default"
            class="comment-avatar"
          />
          <div class="comment-content">
            <div class="comment-header">
              <span class="user-name">{{ comment.user.nickname }}</span>
              <span class="comment-time">{{
                formatTimeAgo(comment.createTime)
              }}</span>
            </div>
            <div class="comment-text">
              {{ comment.content }}
            </div>
            <div class="comment-actions">
              <span class="action-item"
                ><el-icon><Thumb /></el-icon> {{ comment.likeCount }}</span
              >
              <span class="action-item"
                ><el-icon><ChatDotRound /></el-icon> 回复</span
              >
              <span class="action-item"
                ><el-icon><Share /></el-icon> 分享</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐歌单功能已移除 -->
  </div>
</template>

<script setup>
import {
  ChatDotRound,
  Headset,
  Link,
  MuteNotification,
  Picture,
  Share,
  Star,
  VideoPlay,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "../services/api";

// 路由
const route = useRoute();
const router = useRouter();
const goBack = () => {
  // 返回到歌单列表页
  router.push("/playlist");
};
const playlistId = route.params.id;

// 歌单详情相关数据
const playlist = ref({});
const creator = ref({});
const songs = ref([]);
const comments = ref([]);

const currentUser = ref({
  userId: "current_user",
  nickname: "我",
  avatarUrl: "/images/avatars/default.jpg",
});

const newComment = ref("");

// 获取歌单详情（使用api.playlistApi.getPlaylistDetailById）
const fetchPlaylistDetail = async (playlistId) => {
  try {
    const res = await api.playlistApi.getPlaylistDetailById(playlistId);
    // 兼容后端返回格式为 res.data = 歌单对象
    const data = res.data || {};
    playlist.value = {
      playlistId: data.playlistId,
      name: data.playlistName || data.name,
      coverUrl: data.coverUrl,
      description: data.description,
      playCount: data.playCount,
      collectCount: data.collectCount,
      commentCount: data.commentCount,
      songCount: data.songCount,
      createTime: data.createTime,
      tags:
        typeof data.tags === "string" ? data.tags.split(",") : data.tags || [],
    };
    creator.value = data.creator || {};
    comments.value = data.comments || [];

    // 获取歌单歌曲列表
    fetchPlaylistSongs(playlistId);
  } catch (e) {
    console.error(e);
    ElMessage.error("获取歌单详情失败");
  }
};

// 获取歌单歌曲列表
const fetchPlaylistSongs = async (playlistId) => {
  try {
    const res = await api.playlistApi.getPlaylistSongs(playlistId);
    if (res.data) {
      songs.value = res.data.map((song) => ({
        id: song.songId,
        songName: song.songName,
        artistId: song.artistId,
        artistName: song.artistName,
        albumId: song.albumId,
        albumName: song.albumName,
        duration: song.duration,
        coverUrl: song.coverUrl,
        isVip: song.isVip,
      }));
    }
  } catch (e) {
    console.error(e);
    ElMessage.error("获取歌单歌曲列表失败");
  }
};

onMounted(() => {
  fetchPlaylistDetail(playlistId);
});

// 格式化播放次数
const formatPlayCount = (count) => {
  if (count >= 1000000) {
    return `${(count / 1000000).toFixed(1)}M`;
  } else if (count >= 10000) {
    return `${Math.floor(count / 10000)}万`;
  }
  return count;
};

// 格式化时长
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

// 格式化时间（多久前）
const formatTimeAgo = (dateString) => {
  const now = new Date();
  const date = new Date(dateString);
  const diff = Math.floor((now - date) / 1000); // 秒数差

  if (diff < 60) return "刚刚";
  if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;

  return formatDate(dateString);
};

// 推荐歌单功能已移除

// 播放歌曲
const playSong = (song) => {
  ElMessage.success(`播放: ${song.songName}`);
};

// 播放全部歌曲
const playAll = () => {
  ElMessage.success(`开始播放歌单: ${playlist.value.name}`);
};

// 添加到播放列表
const addToPlaylist = (item) => {
  if (item.songName) {
    ElMessage.success(`已添加: ${item.songName} 到播放列表`);
  } else {
    ElMessage.success(`已添加整张歌单到播放列表`);
  }
};

// 收藏歌曲
const likeSong = (song) => {
  ElMessage.success(`已收藏: ${song.songName}`);
};

// 分享歌曲
const shareSong = (song) => {
  ElMessageBox.confirm(`分享歌曲 "${song.songName}" 给好友?`, "分享歌曲", {
    confirmButtonText: "复制链接",
    cancelButtonText: "取消",
    type: "info",
  }).then(() => {
    navigator.clipboard.writeText(`https://musicplatform.com/song/${song.id}`);
    ElMessage.success("歌曲链接已复制到剪贴板");
  });
};

// 跳转到歌曲详情页，带来源页面信息
const goToSongDetail = (songId) => {
  router.push({
    name: "SongDetail",
    params: { id: songId },
    query: { from: router.currentRoute.value.fullPath },
  });
};
</script>

<style scoped>
.playlist-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(to bottom, #f9fafd, #ffffff);
}

.back-button {
  margin-bottom: 20px;
}

.playlist-header {
  display: flex;
  margin-bottom: 40px;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.cover-container {
  position: relative;
  flex-shrink: 0;
  margin-right: 30px;
}

.playlist-cover {
  width: 220px;
  height: 220px;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.cover-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  color: #c0c4cc;
  font-size: 40px;
}

.play-count {
  position: absolute;
  top: 10px;
  right: 10px;
  color: white;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.5);
  padding: 4px 12px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  backdrop-filter: blur(4px);
}

.play-count .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.playlist-info {
  flex: 1;
}

.playlist-title {
  font-size: 28px;
  font-weight: 800;
  margin: 0 0 15px;
  color: #333;
}

.creator-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
}

.creator-avatar {
  margin-right: 10px;
}

.creator-name {
  font-weight: 600;
  color: #333;
  margin-right: 15px;
}

.create-time {
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.play-button {
  background: linear-gradient(135deg, #ff3a7c, #ff6b6b);
  border: none;
  padding: 10px 25px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(255, 58, 124, 0.3);
}

.play-button .el-icon {
  margin-right: 8px;
}

.collect-button,
.share-button {
  background: #f0f2f5;
  color: #333;
  font-weight: 500;
  padding: 10px 20px;
}

.collect-button .el-icon,
.share-button .el-icon {
  margin-right: 8px;
}

.tags-container {
  margin-bottom: 20px;
}

.tags-container .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 12px;
}

.description {
  background: #f9fafd;
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #555;
  border-left: 3px solid #ff6b6b;
}

.section-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f2f5;
}

.songs-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
}

.songs-table :deep(.el-table__row) {
  height: 60px;
}

.songs-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.play-icon-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #f5f7fa;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 auto;
}

.play-icon-cell:hover {
  background: #ff6b6b;
  color: white;
  transform: scale(1.1);
}

.song-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: color 0.3s;
  position: relative;
  padding-right: 25px; /* 为链接图标预留空间 */
}

.song-title:hover {
  color: #ff6b6b;
}

.song-title:hover .song-link-icon {
  opacity: 1;
}

.vip-tag {
  margin-left: 8px;
  font-size: 10px;
  background: linear-gradient(135deg, #ffd700, #ffa500);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
}

.song-link-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 0.3s;
  color: #409eff;
}

.comments-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
}

.comment-count {
  font-size: 16px;
  font-weight: normal;
  color: #666;
}

.comment-input {
  display: flex;
  margin-bottom: 30px;
}

.user-avatar {
  flex-shrink: 0;
  margin-right: 15px;
}

.input-container {
  flex: 1;
}

.expression-icons {
  display: flex;
  gap: 12px;
  color: #666;
  font-size: 18px;
}

.expression-icons .el-icon {
  cursor: pointer;
  transition: color 0.2s;
}

.expression-icons .el-icon:hover {
  color: #ff6b6b;
}

.submit-button {
  padding: 8px 20px;
}

.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #f0f2f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  flex-shrink: 0;
  margin-right: 15px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 8px;
}

.user-name {
  font-weight: 600;
  color: #333;
  margin-right: 10px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  line-height: 1.6;
  color: #333;
  margin-bottom: 12px;
}

.comment-actions {
  display: flex;
  gap: 20px;
  font-size: 13px;
  color: #666;
}

.action-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: color 0.2s;
}

.action-item .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.action-item:hover {
  color: #ff6b6b;
}

/* 推荐歌单相关样式已移除 */
</style>
